<p>
  Hodrick-Prescott Filter decomposes a time series\(y_t\) into two components: the cyclical part(which is short-term) and the trend part(which is long term).
</p>

\[y_t=x _t +c_t\]

<p>
  The filter is the solution to the following optimization problem for \(x_t\)
</p>

\[\min _{x_t}\left[\sum_{t=1}^n(y_t-x_t)^2+\lambda\sum_{t=2}^{n-1}[(x_{t+1}-x_t)-(x_{t}-x_{t-1})^2] \right]\]
<p>
  The second term is the discrete derivative of the trend xt which characterizes the smoothness of the curve. We can rewrite the above formula in vector form:
</p>

\[\min_{\bf x}{\parallel {\bf{y}}-{\bf{x}}\parallel}_2^2+\lambda {\parallel D\bf x\parallel}_2^2\]

<p>
  where \({\bf y}=(y_1,y_2,...,y_n),{\bf x}=(x_1,x_2,...,x_n)\in {\rm I\!R}^n\),\(\parallel\cdot\parallel_2\) is the Euclidean norm. D is the (n-2)*n matrix:
</p>

\[

\left[
\begin{matrix}
1 &amp; -2 &amp; 1 &amp; \\
&amp; 1 &amp; -2 &amp; 1 \\
&amp; &amp; &amp; \ddots &amp;\\
&amp; &amp; &amp; 1 &amp; -2 &amp; 1 \\
&amp; &amp; &amp; &amp; 1 &amp; -2 &amp; 1 \\
\end{matrix}
\right]

\]

<p>
  The solution of this optimization problem is given by solving the following linear system:
</p>

\[y=(I+2\lambda D^TD)^{-1}x\]
<div class="section-example-container">

<pre class="python">def hpfilter(self,X, lamb=1600):
    X = np.asarray(X, float)
    if X.ndim &gt; 1:
    X = X.squeeze()
    nobs = len(X)
    I = sparse.eye(nobs,nobs)
    offsets = np.array([0,1,2])
    data = np.repeat([[1.],[-2.],[1.]], nobs, axis=1)
    K = sparse.dia_matrix((data, offsets), shape=(nobs-2,nobs))
    use_umfpack = True
    self.trend = spsolve(I+lamb*K.T.dot(K), X,use_umfpack=use_umfpack)
    cycle = X - self.trend
</pre>
</div>
